import type { Request, Response } from 'express';
import { UserService } from '../services/user.service';
import { validationResult } from 'express-validator';
import type { AuthenticatedRequest } from '../types/custom';
import { ResponseUtil } from '../utils/response';

const userService = new UserService();

export class UserController {

  constructor() {}

  async register(req: Request, res: Response) {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return ResponseUtil.error(res, errors.array()[0].msg);
    }

    try {
      const { account, password, email = '' } = req.body;
      await userService.register(account, password, email);
      return ResponseUtil.success(res, null, '注册成功');
    } catch (error: any) {
      return ResponseUtil.error(res, error.message);
    }
  }

  async login(req: Request, res: Response) {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return ResponseUtil.error(res, errors.array()[0].msg);
    }

    try {
      const { account, password } = req.body;
      const result = await userService.login(account, password);
      return ResponseUtil.success(res, result, '登录成功');
    } catch (error: any) {
      return ResponseUtil.error(res, error.message);
    }
  }

  async getUserInfo(req: AuthenticatedRequest, res: Response) {
    try {
      const user = await userService.getUserInfo(req.user!.userId);
      return ResponseUtil.success(res, user, '获取用户信息成功');
    } catch (error: any) {
      return ResponseUtil.error(res, error.message);
    }
  }

  async getUserList(req: Request, res: Response) {
    try {
      const pageNo = parseInt(req.query.pageNo as string) || 1;
      const pageSize = parseInt(req.query.pageSize as string) || 10;
      
      const result = await userService.getUserList(pageNo, pageSize);
      return ResponseUtil.success(res, result, '获取用户列表成功');
    } catch (error: any) {
      return ResponseUtil.error(res, error.message);
    }
  }
} 